<!DOCTYPE html>
<html lang="en">
    <head>
        <title>websocket测试</title>
        <meta charset="utf-8" />
    </head>

    <body>
        <input type="text" id="enter"> ||
        <button onclick="sendMessage()">测试</button>
        <script>
            let enter = document.getElementById("enter").value;
            if ('WebSocket' in window) {
                websocket = new WebSocket("ws://localhost:1003//jobSchedule/websocket");
            }
            else {
                alert('当前浏览器 Not support websocket')
            }
            //发送错误时的回调方法
            websocket.onerror = err => {
                console.log(err);
            };
            //连接成功建立后回调方法
            websocket.onopen = event => {
                console.log(event);
            };
            //接收到消息的回调方法
            websocket.onmessage = mess => {
                // document.getElementById('message').innerHTML += sendMessage() + ",时间:"+getNowFormatDate()+'<br/>';
                console.log(mess);
            };
            function sendMessage() {
                websocket.send("1,A客户端发来消息，现在是："+getNowFormatDate());
                // if (websocket.readyState === 1)
                // {
                //
                //     websocket.send(enter+":这是一个测试数据"+getNowFormatDate());
                //
                // }
                // else alert("尚未建立websocket连接，请尝试连接");
            }
            //连接关闭的回调方法
            websocket.onclose = () => {
                console.log("连接关闭");
            };
            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function () {
                websocket.close();
            }
            //获取当前时间
            function getNowFormatDate() {
                var date = new Date();
                var separator1 = "-";
                var separator2 = ":";
                var month = date.getMonth() + 1;
                var strDate = date.getDate();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                var currentdate = date.getFullYear() + separator1 + month + separator1 + strDate
                    + " " + date.getHours() + separator2 + date.getMinutes()
                    + separator2 + date.getSeconds();
                return currentdate;
            }
        </script>
    </body>
</html>